package net.zhengxinyun.performance.service.indicators;

import com.sirdc.modules.utils.ObjectUtils;
import net.zhengxinyun.performance.Util.DateUtils;
import net.zhengxinyun.performance.Util.StringUtils;
import net.zhengxinyun.performance.Util.Util;
import net.zhengxinyun.performance.core.Result;
import net.zhengxinyun.performance.core.ResultUtils;
import net.zhengxinyun.performance.entity.CountryUnitScoreEntity;
import net.zhengxinyun.performance.entity.DepartmentEntity;
import net.zhengxinyun.performance.entity.RolePerEntity;
import net.zhengxinyun.performance.entity.UserEntity;
import net.zhengxinyun.performance.filter.CountryUnitIndicatorsFilter;
import net.zhengxinyun.performance.filter.CountryUnitScoreFilter;
import net.zhengxinyun.performance.filter.DepartmentFilter;
import net.zhengxinyun.performance.mapper.Department.DepartmentEntityMapper;
import net.zhengxinyun.performance.mapper.Indicators.CountryUnitScoreEntityMapper;
import net.zhengxinyun.performance.mapper.login.RolePerMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import java.util.*;
import java.util.stream.Collectors;


@Service
public class CountryUnitScoreServiceImpl implements CountryUnitScoreService {

    private CountryUnitScoreEntityMapper countryUnitScoreEntityMapper;
    private DepartmentEntityMapper departmentEntityMapper;


    @Autowired
    private DepartmentEntityMapper departMapper;

    @Autowired
    private RolePerMapper rolePerMapper ;

    @Autowired
    public CountryUnitScoreServiceImpl(DepartmentEntityMapper departmentEntityMapper,CountryUnitScoreEntityMapper countryUnitScoreEntityMapper) {
        this.countryUnitScoreEntityMapper = countryUnitScoreEntityMapper;
        this.departmentEntityMapper=departmentEntityMapper;
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public String delete(CountryUnitScoreEntity countryUnitScoreEntity) {
        int i = countryUnitScoreEntityMapper.deleteByPrimaryKey(countryUnitScoreEntity.getId());
        if (i == 0) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "删除失败，请联系管理员";
        }
        return "删除成功";
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public int insert(CountryUnitScoreEntity record) {

        //将以前记录的分数记录状态改变
        CountryUnitScoreFilter filter = new CountryUnitScoreFilter();
        filter.setIndexId(record.getIndexId());
        filter.setDateTime(record.getDateTime());
        List<CountryUnitScoreFilter> scoreFilters = countryUnitScoreEntityMapper.query(filter);
        if (ObjectUtils.isNotBlank(scoreFilters)) {
            for (CountryUnitScoreFilter item : scoreFilters) {
                CountryUnitScoreEntity entity = new CountryUnitScoreEntity();
                entity.setVaild("0");//无效
                entity.setId(item.getId());
                int updateCode = countryUnitScoreEntityMapper.updateByPrimaryKeySelective(entity);
                if (updateCode == 0) {
                    System.out.println("保存失败");
                }

            }
        }

        record.setVaild("1");
        record.setAudit("1");

        return countryUnitScoreEntityMapper.insert(record);
    }


    public String insertByBatch(List<CountryUnitScoreEntity> countryUnitScoreEntity) {
        if (countryUnitScoreEntity != null && countryUnitScoreEntity.size() > 0) {

            CountryUnitScoreFilter filter = new CountryUnitScoreFilter();
            filter.setIndexId(countryUnitScoreEntity.get(0).getIndexId());
            filter.setDateTime(countryUnitScoreEntity.get(0).getDateTime());
            List<CountryUnitScoreFilter> scoreFilters = countryUnitScoreEntityMapper.query(filter);
            if (ObjectUtils.isNotBlank(scoreFilters)) {
                for (CountryUnitScoreFilter item : scoreFilters) {
                    CountryUnitScoreEntity entity = new CountryUnitScoreEntity();
                    entity.setVaild("0");//无效
                    entity.setId(item.getId());
                    int update = countryUnitScoreEntityMapper.updateByPrimaryKeySelective(entity);
                    if (update == 0) {
                        System.out.println("保存失败");
                    }

                }
            }
            for (CountryUnitScoreEntity entity : countryUnitScoreEntity) {

                String responsibilityId = entity.getResponsibilityId();
                DepartmentFilter departmentFilter = new DepartmentFilter();
                departmentFilter.setDepartcode(responsibilityId);
                List<DepartmentFilter> filters = departmentEntityMapper.query(departmentFilter);
                if (filters.size() != 1) {
                    return ( "添加失败,请联系管理员");
                }
                entity.setDepartment(filters.get(0).getDepartment());
                entity.setAudit("1");
                entity.setVaild("1");//有效
            }

            int i = countryUnitScoreEntityMapper.insertByBatch(countryUnitScoreEntity);
            if (i == 0) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return "批量插入失败，请联系管理员";
            }
            return "批量插入成功";
        } else {
            return "没有需要插入的数据，请联系管理员";
        }
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public int insertSelective(CountryUnitScoreEntity record) {
        return countryUnitScoreEntityMapper.insertSelective(record);
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public CountryUnitScoreEntity selectByPrimaryKey(Long id) {
        return countryUnitScoreEntityMapper.selectByPrimaryKey(id);
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public int updateByPrimaryKeySelective(CountryUnitScoreEntity record) {
        return countryUnitScoreEntityMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * This method was generated by MyBatis Generator.
     * This method corresponds to the database table inv_country_unit_score
     *
     * @mbg.generated Mon Jun 24 10:50:28 CST 2019
     */
    public int update(CountryUnitScoreEntity record) {
        return countryUnitScoreEntityMapper.updateByPrimaryKey(record);
    }

    /**
     * 查询所有的县直属单位
     *
     * @return
     */
    public List <DepartmentEntity> queryCountryUnit() {
        return countryUnitScoreEntityMapper.queryCountryUnit();
    }

    @Override
    public List<CountryUnitScoreEntity> countCountryUnitScore(Long id) {
        return countryUnitScoreEntityMapper.countCountryUnitScore(id);
    }

    @Override
    public List<Map<Integer, String>> queryIndicators() {

        return countryUnitScoreEntityMapper.queryIndicators();
    }

    @Override
    public List<Map<String, Object>> queryScoreList(CountryUnitScoreFilter filter) {
        List<CountryUnitScoreEntity> scoreList = countryUnitScoreEntityMapper.queryScoreList(filter);
        List<Map<String, Object>> listMap = new ArrayList<>();
        if (scoreList != null && scoreList.size() > 0) {
            for (CountryUnitScoreEntity scoreEntity : scoreList) {
                HashMap<String, Object> map = new HashMap<>();

                map.put("department", scoreEntity.getDepartment());
                map.put("score", scoreEntity.getScore());
                map.put("indexId", scoreEntity.getIndexId());
                map.put("departCode", scoreEntity.getResponsibilityId());
                map.put("dateTime", scoreEntity.getDateTime());
                map.put("monthTime", scoreEntity.getMonthTime());
                listMap.add(map);
            }
        }
        return listMap;
    }

    @Override
    public int countScore(CountryUnitScoreFilter filter) {
        return countryUnitScoreEntityMapper.countScore(filter);
    }




    /**
     * 首页展示数据
     * @param filter
     * @return
     */
    @Override
    public List<CountryUnitScoreFilter> queryScoreHomeDate(CountryUnitScoreFilter filter, UserEntity userEntity) {



        List<CountryUnitScoreFilter> list  = countryUnitScoreEntityMapper.queryScoreHomeDate(filter);

        if("admin".equals(userEntity.getUserPermissions()))
        {
            return  list;
        }

        RolePerEntity role  = rolePerMapper.selectByPrimaryKey(userEntity.getRoleid());
        String index = "";
        if(ObjectUtils.isNotBlank(role))
        {
            index =role.getDepartIndex();
        }else {
            index = userEntity.getDepartIndex();
        }

        HashMap<String,Object> map = Util.getIndexIdMap(index);
        List<CountryUnitScoreFilter>  listscore = new ArrayList<>();

        for (CountryUnitScoreFilter item: list)
        {
            String id1 = item.getId().toString();
            Object id2 = map.get(id1);
            if(ObjectUtils.isBlank(id2))
                continue;

            if(id1.equals(id2.toString()))
            {
                listscore.add(item);
            }

        }
        return listscore;
    }

    @Override
    public int queryForCount(CountryUnitScoreFilter filter) {
        return countryUnitScoreEntityMapper.queryForCount(filter);
    }

    /**
     * 保存导入的分数
     * @param list
     * @param id
     */
    @Override
    @Transactional
    public String saveImportUnitScore(List<CountryUnitScoreEntity> list, Long id) {

        String names = "";

        CountryUnitScoreFilter filter  = new CountryUnitScoreFilter();
        filter.setId(id);
        filter.setDateTime(DateUtils.getLastMonth());
        filter.setIndexId(id.toString());
        List<CountryUnitScoreEntity>  templist = countryUnitScoreEntityMapper.selectByIndexId(filter);
        if(ObjectUtils.isNotBlank(templist))
        {
            for ( CountryUnitScoreEntity item: templist)
            {
                item.setVaild("0");
                countryUnitScoreEntityMapper.updateByPrimaryKey(item);
            }
        }

        for(CountryUnitScoreEntity item: list)
        {
            /**
             * 匹配单位
             */
           ;
            List<DepartmentEntity> depart = departMapper.getDepartByNameList( item.getDepartment()); //责任 id；
            if(ObjectUtils.isBlank(depart))
            {
                names=names+","+item.getDepartment();
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  "未能匹配到考核单位["+item.getDepartment()+"]，请勿修改模板中考核单位的名称";
              //  System.out.println("----------------找不到责任单位------------"+item.getDepartment()+"--------------------------");
                //continue;
            }else if(depart.size()>1) {
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return  "根据考核单位["+item.getDepartment()+"]匹配到多个单位，请勿修改模板中考核单位的名称";
            }
            item.setDepartCode(depart.get(0).getDepartcode());
            item.setIndexId(id.toString());
            item.setDateTime(DateUtils.getLastMonth());
            item.setAudit("1");
            item.setVaild("1");
             countryUnitScoreEntityMapper.insert(item);


        }
        return  "ok";

    }





    @Override
    public List<CountryUnitScoreFilter> query(CountryUnitScoreFilter filter) {
        return countryUnitScoreEntityMapper.query(filter);
    }

    @Override
    public List<HashMap<String,Object>> queryAllData(CountryUnitScoreFilter filter) {
        String[] month = Util.MONTH;
        DepartmentFilter departmentFilter = new DepartmentFilter();
        departmentFilter.setDepartType("县直单位");
        List<DepartmentFilter> query = departMapper.query(departmentFilter);
        List<HashMap<String,Object>> dataList  = new ArrayList<>();
        for (DepartmentFilter depart : query) {

            HashMap<String,Object> dataMap = new HashMap<>();
            filter.setDepartCode(depart.getDepartcode());
            dataMap.put("department",depart.getDepartment());
            filter.setDateTime(null);
            List<CountryUnitScoreFilter> list = countryUnitScoreEntityMapper.query(filter);
            for (CountryUnitScoreFilter scoreFilter : list) {
                for (String mon : month) {
                    if(scoreFilter.getDateTime().endsWith(mon))
                    {
                        dataMap.put("month"+mon,StringUtils.isBlank(scoreFilter.getScore())?null:scoreFilter.getScore());
                    }
                }
            }
            dataList.add(dataMap);
        }

        return  dataList;
    }

    //单位得分
    @Override
    public List<CountryUnitScoreFilter> getdeptScore(Long indexId, String dateTime) {
        return countryUnitScoreEntityMapper.getdeptScore(indexId,dateTime);
    }
}